/**
 * @author : andy
 * @description : 标签页功能
 */
import { useRoute , useRouter , type RouteLocationNormalized } from 'vue-router';
import { useTabbarStore } from './tabbarStore';
import { useAccessStore } from '@/stores/access/access';
import { watch , toRaw, computed, nextTick } from 'vue';
import { useTabbarPathStore } from './useTabbarPath';
import { cloneDeep , omit } from 'lodash-es';
export function useTabbar () {
  const route = useRoute();
  const router = useRouter();
  const tabbarStore = useTabbarStore();
  const accessStore = useAccessStore();
  const { addPath , closePath , updatePath , tabbarPathList , hasPath }  = useTabbarPathStore();
  const currentTabs = computed(() => {
    return tabbarStore.tabs;
  });
  /**
   * 点击标签页
   * @param tab route对象
   */
  const clickTab = (tab: RouteLocationNormalized) => {
    router.push(tab.fullPath);
  }
  /**
   * 关闭标签页
   * @param tab route对象
   */
  const closeTab = (tab: RouteLocationNormalized): number => {
    closePath(tab.fullPath);
    return tabbarStore.closeTab(tab);
  }
  /**
   * 更新tab
   * @param oldIndex 旧索引
   * @param newIndex 新索引
   */
  const updateTab = (oldIndex: number , newIndex: number) => {
    tabbarStore.updateTab(oldIndex , newIndex);
  }
  /**
   * 获取当前被激活的标签页
   * @param key fullPath，路由路径
   */
  const getActiveTab = (key: string): RouteLocationNormalized => {
    return currentTabs.value.find(tab => tab.fullPath === key) as RouteLocationNormalized;
  }
  /**
   * 关闭当前激活标签页左边的所有标签
   * @param fullPath 路由路径
   */
  const closeLeftAllTabs = (fullPath: string) => {
    const cloneTabs: RouteLocationNormalized[] = cloneDeep(toRaw(currentTabs.value));
    const index = cloneTabs.findIndex(tab => tab.fullPath === fullPath);
    if (index >= 1) {
      for (let i = 0 ; i < index ; i++) {
        const tab = cloneTabs[i];
        if (!tab.meta.fixed) {
          closeTab(tab);
        }
      }
    }
  }
  /**
   * 关闭当前激活标签页右边的所有标签
   * @param fullPath 路由路径
   */
  const closeRightAllTabs = (fullPath: string) => {
    const cloneTabs: RouteLocationNormalized[] = cloneDeep(toRaw(currentTabs.value));
    const index = cloneTabs.findIndex(tab => tab.fullPath === fullPath);
    if (index < currentTabs.value.length - 1) {
      for (let i = index + 1 ; i < cloneTabs.length ; i++) {
        const tab = cloneTabs[i];
        if (!tab.meta.fixed) {
          closeTab(tab);
        }
      }
    }
  }
  const closeAllTabs = () => {
    const cloneTabs: RouteLocationNormalized[] = cloneDeep(toRaw(currentTabs.value));
    for (let i = 0 ; i < cloneTabs.length ; i++) {
      const tab = cloneTabs[i];
      if (!tab.meta.fixed) {
        closeTab(tab);
      }
    }
  }
  const updateTabMeta = (fullPath: string , meta: Record<string , unknown>) => {
    const tab = currentTabs.value.find(tab => tab.fullPath === fullPath);
    if (tab) {
      tab.meta = {
        ...tab.meta,
        ...meta
      }
    }
  }
  /**
   * 关闭当前标签页并打开下一个标签页
   * @param tab route对象
   */
  const closeAndOpenNextTab = (tab: RouteLocationNormalized) => {
    if (!tab) {
      return;
    }
    if (tab?.meta.fixed) {
      return;
    }
    closeTab(tab);
    if (tab.fullPath === route.fullPath) {
      if (tabbarPathList.value.length > 0) {
        router.push(tabbarPathList.value[tabbarPathList.value.length - 1]);
      } else {
        // 不存在，表示已经删除完了，那么跳转到首页
        nextTick(() => {
          router.replace('/');
          setTimeout(() => {
            window.location.href = '/';
          })
        });
      }
    }
  }
  watch(() => route.path , () => {
    const meta = route.matched?.[route.matched.length - 1]?.meta;
    const cloneRoute = cloneDeep(toRaw(omit(route , ['matched' , 'redirectedFrom'])));
    // 通过 accessRoutes 获取 iframe路由信息
    const iframeRoute = accessStore.accessRoutes.find(item => item.path === decodeURIComponent(cloneRoute.params.path as string));
    if (iframeRoute) {
      cloneRoute.meta = {
        ...cloneRoute.meta,
        ...iframeRoute.meta
      }
      tabbarStore.addTab({
        ...cloneRoute
      } as RouteLocationNormalized);
    } else {
      // 非iframe路由
      tabbarStore.addTab({
        ...cloneRoute,
        meta : meta || route.meta
      } as RouteLocationNormalized);
    }
    if (hasPath(route.fullPath)) {
      updatePath(route.fullPath);
    } else {
      addPath(route.fullPath);
    };
  } , {immediate : true})
  return {
    currentTabs,
    clickTab,
    closeTab,
    getActiveTab,
    closeAndOpenNextTab,
    closeLeftAllTabs,
    closeRightAllTabs,
    closeAllTabs,
    updateTabMeta,
    updateTab
  }
}